﻿using System;
using System.Collections.Generic;
using System.Text;
using ZX.CRM.Library;
using ZX.BLL.Extend;
using ZX.DBModule;
using System.IO;
using ZX.Common;
using ZX.SYS.Library;
using System.Data;
using ZX.DAL.DBExtend;
using System.Text;
using System.IO;
using System.Net;
using System.Web;
using System.Configuration;
namespace ZX.CRM.Bussiness
{
    public class MQproccess : BLL.Extend.BaseBussnies
    {
        public static readonly string serverUser = ConfigurationManager.AppSettings["MessageUser"].ToString();
        public static readonly string serverPass = ConfigurationManager.AppSettings["MessagePass"].ToString();
        public static readonly string serverURL = ConfigurationManager.AppSettings["MessageURL"].ToString();

        private readonly static int TIMEOUT = 15000;
        private CookieContainer _cookieCon = new CookieContainer();
        private CredentialCache _credentials;
        public DataTable getMQ_OrgBodyList(string userid, string otid)
        {
            DbSql dq = new DbSql();
            string condition = "";
            if (userid != "" || userid != string.Empty)
            {
                condition = "and AddUser='" + userid + "'";
            }
            if (otid != "")
                condition += "and otid='" + otid + "'";
            return dq.ExecuteQuery(@"SELECT [obid]
                                      ,[otid]
                                      ,[mphone]
                                      ,[name]
                                      ,[userid]
                                      ,[Col1]
                                      ,[addtime]
                                      ,[AddUser]
                                      ,[otname]
                                  FROM  [V_MQ_OrgBody] where 1=1" + condition);
        }


        public DataTable getMessageList(string userid, string status)
        {
            DbSql dq = new DbSql();
            string condition = "";
            if (userid != "" || userid != string.Empty)
            {
                condition = "and senduser='" + userid + "'";
            }
            if (status != "")
                condition += "and mstatus=" + status;
            return dq.ExecuteQuery(@"SELECT [mbid]
                                    ,[title]
                                    ,[content]
                                    ,[AddUser]
                                    ,[reuser]
                                    ,[sendtime]
                                    ,[looktime]
                                    ,[mstatus]
                                    ,[mtype]=CASE   [mtype]   WHEN   0  THEN   '短信 '  WHEN   1  THEN   '邮件 ' ELSE   '系统消息'   END
                                    ,[obid]
                                    ,[name]
                                    ,[mphone]
                                    ,[userid]
                                FROM [V_MQmessage] where 1=1" + condition);
        }

        //自动执行未发生短信的发送
        public void AutoExe()
        {
            DbSql dq = new DbSql();
            DataTable dt = getMessageList("", "0");
            string sql = "";
            for (int i = 0; i < dt.Rows.Count;i++ )
            {
                if (sendmessage(dt.Rows[i]["mphone"].ToString(), dt.Rows[i]["content"].ToString()) == "0")
                {
                    sql = "update MQ_MessageBody set mstatus=1 where mbid='" + dt.Rows[i]["mbid"].ToString() + "'";
                    dq.ExecuteSql(sql);
                }
            }
        }

        //发送短信
        public string sendmessage(string phone, string msg)
        {
            MQproccess mq = new MQproccess();
            string Msg = System.Web.HttpUtility.UrlEncode(msg, System.Text.Encoding.UTF8);
            return mq.GetPageContent(serverURL + "?username=" + serverUser + "&password=" + serverPass + "&mobile=" + phone
                + "&content=" + Msg + "&Extcode=&senddate=", string.Empty);
        }
        //插入数据库
        public void insert(string mes, Guid reuserid, DateTime sendtime, string reusername, string phone, int havesend,Guid userid,string username)
        {
            MQ_OrgBody mob = new MQ_OrgBody();
            mob.obid = Guid.NewGuid();
            mob.name = reusername;
            mob.userid = reuserid;
            mob.mphone = phone;
            mob.addtime = DateTime.Now;
            mob.byuser = userid; 
            mob.Col1 = username;//发送人姓名
            MQ_MessageBody mmb = new MQ_MessageBody();
            mmb.mbid = Guid.NewGuid();
            mmb.reuser = mob.obid;
            mmb.AddUser = userid;
            mmb.content = mes;
            mmb.mstatus = havesend;
            mmb.sendtime = sendtime;
            mmb.mtype = 0;//0为短信
            BaseBussnies bmob = new BaseBussnies(mob);
            BaseBussnies bmmb = new BaseBussnies(mmb);

            bmob.Insert();
            bmmb.Insert();
        }

        /// <summary>
        /// 通过url请求数据
        /// </summary>
        /// <param name="url">被请求页面的url</param>
        /// <param name="proxyServer">代理服务器</param>
        /// <returns>返回页面内容</returns>
        public string GetPageContent(string url, string proxyServer)
        {
            StringBuilder ret = new StringBuilder("");
            HttpWebResponse rsp = null;

            try
            {
                Uri uri = new Uri(url);
                HttpWebRequest req = (HttpWebRequest)WebRequest.Create(uri);
                if (!string.IsNullOrEmpty(proxyServer))
                {
                    req.Proxy = new WebProxy(proxyServer);
                }
                req.CookieContainer = this._cookieCon;
                req.Headers.Add("Accept-Language: zh-cn");
                req.AllowAutoRedirect = true;
                req.Timeout = TIMEOUT;

                if (this._credentials != null)
                {
                    req.PreAuthenticate = true;
                    req.Credentials = this._credentials;
                }
                rsp = (HttpWebResponse)req.GetResponse();

                Stream rspStream = rsp.GetResponseStream();
                StreamReader sr = new StreamReader(rspStream, System.Text.Encoding.Default);

                //获取数据
                Char[] read = new Char[256];
                int count = sr.Read(read, 0, 256);
                while (count > 0)
                {
                    ret.Append(read, 0, count);
                    count = sr.Read(read, 0, 256);
                }
            }
            catch (Exception e)
            {
                ret.Append(e.Message);
            }
            finally
            {
                if (rsp != null)
                {
                    rsp.Close();
                }
            }
            return ret.ToString();
        }
    }
}
